package com.example.back.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.example.back.dto.req.GetHospitalDataReq;
import com.example.back.dto.req.GetServiceDataReq;
import com.example.back.dto.resp.*;
import com.example.back.mapper.MainMapper;
import com.example.back.service.MainService;
import com.example.common.enums.AType;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author wxy
 * @Date 2021/1/13 13:53
 * @Version 1.0
 */
@Service
public class MainServiceImpl implements MainService {

    @Resource
    MainMapper mainMapper;

    /**
     * 疾病列表
     */
    @Override
    public GetDataRsp GetData() {
        //当天的结束时间
        DateTime dateTime = DateUtil.beginOfDay(new Date());
        DateTime dateTimeWeek = DateUtil.beginOfWeek(new Date());
        DateTime dateTimeMonth = DateUtil.beginOfMonth(new Date());
        //问诊订单
        Integer countDay = mainMapper.countDay(dateTime);
        Integer countWeek = mainMapper.countDay(dateTimeWeek);
        Integer countMont = mainMapper.countDay(dateTimeMonth);
        InquiryRsp inquiryRsp = new InquiryRsp();
        inquiryRsp.setToday(countDay);
        inquiryRsp.setWeek(countWeek);
        inquiryRsp.setMonth(countMont);

        //在线情况
        Integer countPatint = mainMapper.countPatint();
        Integer countDocter = mainMapper.countDocter();
        Integer countPharmacist = mainMapper.countPharmacist();
        OnLineRsp onLineRsp = new OnLineRsp();
        onLineRsp.setPatient(countPatint);
        onLineRsp.setPharmacist(countPharmacist);
        onLineRsp.setDoctor(countDocter);

        //机构排名
        List<DepartOrderRsp> departOrderRspList = mainMapper.DepartOrder();
        List<DepartOrderRsp> departOrderRsps = new ArrayList<>();
        Map<String, List<DepartOrderRsp>> collect = departOrderRspList.stream().collect(Collectors.groupingBy(DepartOrderRsp::getName));
        for (String s : collect.keySet()) {
            DepartOrderRsp departOrderRsp = new DepartOrderRsp();
            departOrderRsp.setName(s);
            departOrderRsp.setDoctor(collect.get(s).size());
            departOrderRsp.setService(collect.get(s).stream().mapToInt(DepartOrderRsp::getService).sum());
            departOrderRsp.setPrescription(collect.get(s).stream().mapToInt(DepartOrderRsp::getPrescription).sum());
            departOrderRsp.setPraise(collect.get(s).stream().mapToDouble(DepartOrderRsp::getPrescription).average().getAsDouble());
            departOrderRsps.add(departOrderRsp);
        }
        departOrderRsps = departOrderRsps.stream().sorted(Comparator.comparing(DepartOrderRsp::getService).thenComparing(DepartOrderRsp::getPraise).reversed()).limit(5).collect(Collectors.toList());

        List<DoctorOrderRsp> doctorOrderRspList = mainMapper.docterOrderBy();
        GetDataRsp getDataRsp = new GetDataRsp();
        getDataRsp.setInquiry(inquiryRsp);
        getDataRsp.setOnLine(onLineRsp);
        getDataRsp.setDepartOrder(departOrderRsps);
        getDataRsp.setDoctorOrder(doctorOrderRspList);
        return getDataRsp;
    }

    /**
     *
     */
    @Override
    public GetHospitalDataRsp GetHospitalData(GetHospitalDataReq getHospitalDataReq) {
        Date beg;
        Date end;
        if (ObjectUtils.isEmpty(getHospitalDataReq.getBeg())) {
            beg = DateUtil.beginOfDay(new Date());
            end = DateUtil.endOfWeek(new Date());
        } else {
            beg = DateUtil.parse(getHospitalDataReq.getBeg());
            end = DateUtil.parse(getHospitalDataReq.getEnd());
        }
        List<Double> TodayService = mainMapper.TodayService(DateUtil.beginOfDay(new Date()));

        List<Double> TodayDrug = mainMapper.TodayDrug(DateUtil.beginOfDay(new Date()));

        List<OrderMainRspT> orderMainList = mainMapper.orderMainList(beg, end);
        for (OrderMainRspT orderMainRspT : orderMainList) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(orderMainRspT.getDate());
            try {
                Date date = simpleDateFormat.parse(format);
                orderMainRspT.setDate(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        List<HospitalDayList> lists = new ArrayList<>();
        Map<Date, List<OrderMainRspT>> collect = orderMainList.stream().collect(Collectors.groupingBy(OrderMainRspT::getDate));
        for (Date date : collect.keySet()) {
            HospitalDayList hospitalDayList = new HospitalDayList();
            hospitalDayList.setDate(DateUtil.format(date, "yyyy-MM-dd"));
            hospitalDayList.setService(collect.get(date).stream().mapToDouble(OrderMainRspT::getAskMoney).sum());
            List<OrderMainRspT> orderMainRspTS = collect.get(date);
            Double d = 0.0;
            for (OrderMainRspT orderMainRspT : orderMainRspTS) {
                List<Double> doubles = mainMapper.queryByOrderNo(orderMainRspT.getOrderNo());
                d += doubles.stream().mapToDouble(Double::doubleValue).sum();
            }
            hospitalDayList.setDrug(d);
            lists.add(hospitalDayList);
        }

        GetHospitalDataRsp getHospitalDataRsp = new GetHospitalDataRsp();
        getHospitalDataRsp.setHospitalDayList(lists.stream().sorted(Comparator.comparing(HospitalDayList::getDate)).collect(Collectors.toList()));
        getHospitalDataRsp.setTodayService(TodayService.stream().mapToDouble(Double::doubleValue).sum());
        getHospitalDataRsp.setTodayDrug(TodayDrug.stream().mapToDouble(Double::doubleValue).sum());

        return getHospitalDataRsp;
    }

    /**
     * 服务统计
     */
    @Override
    public List<GetServiceDataResp> GetServiceData(GetServiceDataReq req) {
        String strsbeg = req.getBeg();
        String strsend = req.getEnd();
        Date now = new Date();
        Date send = DateUtil.offsetDay(now, 1);
        Date sbeg = DateUtil.offsetDay(send, -7);
        if (!StringUtils.isEmpty(strsbeg) && !StringUtils.isEmpty(strsbeg)) {
            sbeg = DateUtil.parseDate(strsbeg);
            send = DateUtil.offsetDay(DateUtil.parseDate(strsend), 1);
        }
        List<GetServiceDataCountResp> countList = mainMapper.GetServiceData(sbeg, send);
        List<GetServiceDataResp> list = new ArrayList<>();
        long sSum = countList.stream().map(GetServiceDataCountResp::getCount).count();
        Arrays.stream(AType.values()).forEach(c -> {
            String percentage;
            long count = countList.stream().filter(f -> f.getAType().equals(c.getValue())).count();
            if (count > 0L) {
                BigDecimal bigDecimal = new BigDecimal(count).multiply(new BigDecimal(100)).divide(new BigDecimal(sSum), 2, BigDecimal.ROUND_DOWN);
                percentage = bigDecimal.toString();
            } else {
                percentage = "0";
            }
            GetServiceDataResp resp = new GetServiceDataResp();
            resp.setATypeName(c.getDescription());
            resp.setPercentage(percentage);
            list.add(resp);
        });
        return list;
    }
}
